package ve.basura.entrada.aop;

import java.util.Calendar;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;


@Aspect
public class AopLogger {

	Log log;
	Calendar startDateTime;
	Calendar endDateTime;

	protected AopLogger() {
	}
	
	 
	   @Around ("execution(*  ve.basura.entrada..*.*(..))")
	    private Object logging(ProceedingJoinPoint pjp)throws Throwable {
		   
		   String identificadorClaseMetodo = pjp.getTarget().getClass().getSimpleName() + "." +pjp.getSignature().getName();
		   
		   Object[] args =  pjp.getArgs();
		   
		   String argumentosString="| ";
		   
		   for(Object argumento : args){
			   argumentosString+=argumento+" | ";
		   }
		   
		   String identificadorClaseMetodoArgs=null;
		   if(args.length>0)identificadorClaseMetodoArgs = identificadorClaseMetodo + ", whit args --> " + argumentosString;
		   else identificadorClaseMetodoArgs = identificadorClaseMetodo ;
		   
		   log.info("Executing method: " + identificadorClaseMetodoArgs  );

		   startDateTime = Calendar.getInstance();

		   Object retVal;
	
		   try{
		      retVal = pjp.proceed();
		   }catch(Exception e){
			 log.fatal(e.getMessage());
			 throw e;
		   }
	
		   endDateTime = Calendar.getInstance();

		   log.info("Method execution ended : " + identificadorClaseMetodo +",whit returning val --> "+ retVal +", duration --> "+ ((endDateTime.getTimeInMillis()-startDateTime.getTimeInMillis())/1000 )+" seconds."  );
 		   return retVal;
	   }


	/**
	 * @return the log
	 */
	public Log getLog() {
		return log;
	}


	/**
	 * @param log the log to set
	 */
	public void setLog(Log log) {
		this.log = log;
	}
	   
}